import logging

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from . import constants

# Create your views here.

logger = logging.getLogger('django')


class SMSCodeView(APIView):
    """
    短信验证
    """

    def get(self, request, phone):
        # 流程：
        # 1 生成验证码
        # 2 创建redis连接对象
        # 3 把验证码放到redis数据库
        # 4 利用短信网关发送短信验证码
        # 5 响应

        # 创建redis连接
        from django_redis import get_redis_connection
        # 调用全局配置中'smscode'的redis模版
        redis_conn = get_redis_connection('smscode')

        # issue Day 3.1 校验，从redis中查看此手机号是否已经发送过
        sms_flag = redis_conn.get("sms_flag_{}".format(phone))
        if sms_flag:
            return Response({'message': '手机频繁发送，请稍后'}, status=status.HTTP_400_BAD_REQUEST)

        # 生成验证码
        from random import randint
        smscode = randint(0, 999999)
        logger.info(smscode)

        # 创建redis管道
        pl = redis_conn.pipeline()

        # 把验证码放到redis数据库
        # redis_conn.setex("sms_{}".format(phone), constants.SMS_CODE_REDIS_EXPIRES, smscode)
        pl.setex("sms_{}".format(phone), constants.SMS_CODE_REDIS_EXPIRES, smscode)

        # issue Day 3.1 存储一个标记，表示此手机已经发送过短信，有效期60s
        # redis_conn.setex("sms_flag_{}".format(phone), constants.SMS_FLAG_REDIS_EXPIRES, 1)
        pl.setex("sms_flag_{}".format(phone), constants.SMS_FLAG_REDIS_EXPIRES, 1)

        # 执行redis管道
        pl.execute()

        # 利用短信网关发送短信验证码，需要导入容联云的SDK
        # 容联云 https://www.yuntongxun.com/member/main
        # 下面方法已经加入到celery的异步任务中
        """
        from BookshopDrf.libs.ronglian_sms_sdk.SmsSDK import SmsSDK
        # SmsSDK().sendMessage(self, tid: str, mobile: str, datas: tuple)
        # mobile: str 手机号； datas: tuple 数据；tid: str 短信模版
        accId = '8a216da87de15752017e0181a8cb07e5'
        accToken = '5db79b9ac97246dfba4095cab868aa55'
        appId = '8a216da87de15752017e0181a9e107eb'

        def send_message():
            sdk = SmsSDK(accId, accToken, appId)
            tid = '1'
            mobile = '17786378545'
            datas = (smscode,)
            resp = sdk.sendMessage(tid, mobile, datas)
            print(resp)

        send_message()
        """
        # 触发异步任务，将异步任务添加到celery队列中
        from celery_broker.sms.tasks import send_sms_code

        # 不能写成send_sms_code(),这种写法的意思是只是调用普通函数，没有触发队列
        # 触发celery队列的写法
        send_sms_code.delay(phone, smscode)

        # 响应
        return Response({'message': 'OK'})

        # 测试
        # http://127.0.0.1:8000/smscode/17786378545/
